"""
FastAPI 主应用
"""
import logging
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from config import config
from database import init_db
from routers import stock_router
from routers import push_router

# 配置日志
logging.basicConfig(
    level=getattr(logging, config.LOG_LEVEL),
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

logger = logging.getLogger(__name__)

# 创建 FastAPI 应用
app = FastAPI(
    title="股票分析 API",
    description="提供股票数据、技术分析和交易信号",
    version="1.0.0"
)

# 配置 CORS（允许 Android App 跨域访问）
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境应该设置具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(stock_router.router, prefix="/api", tags=["stocks"])
app.include_router(push_router.router, prefix="/api", tags=["push"])

@app.on_event("startup")
async def startup_event():
    """应用启动时执行"""
    logger.info("🚀 启动股票分析 API...")
    init_db()  # 初始化数据库
    logger.info("✅ 数据库初始化完成")
    
    # 启动异步定时任务调度器
    from async_scheduler import async_scheduler
    async_scheduler.start()
    logger.info("✅ 异步定时任务调度器已启动")

@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭时执行"""
    logger.info("👋 关闭股票分析 API")
    
    # 停止异步定时任务
    from async_scheduler import async_scheduler
    async_scheduler.stop()
    logger.info("✅ 异步定时任务调度器已停止")

@app.get("/")
async def root():
    """根路径"""
    return {
        "message": "股票分析 API",
        "version": "1.0.0",
        "docs": "/docs"
    }

@app.get("/health")
async def health_check():
    """健康检查"""
    return {"status": "healthy"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "main:app",
        host=config.API_HOST,
        port=config.API_PORT,
        reload=config.API_DEBUG
    )

